import { Modal, Tag, Drawer, Button, Spin, message, Form, Image, Card, Flex, Divider } from 'antd'
import ExcelTable from '@components/exportExcel'
import LogForm from '@/pages/setting/logManage/components/LogForm'
import { useRef, useState } from 'react'
import { ActionType, ProFormInstance } from '@ant-design/pro-components'
import { getUserMsg } from '@/apis/accessManagement/message/userMsg'
import { revokeMsg } from '@/apis/accessManagement/message/userMsg'
import dayjs from 'dayjs'
import { storage } from '@/utils/Storage'

const UserMessage: React.FC = () => {
  useRef<ActionType>()
  useRef<ProFormInstance>()
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [open, setOpen] = useState(false)
  const [currentMulInfo, setCurrentMulInfo] = useState<any>({})
  //   const [sortedData, setSortedData] = useState([])
  const actionRef = useRef()

  // 提交撤回消息
  const subRevoke = async (record: any) => {
    setLoading(true)
    try {
      const response = await revokeMsg({
        conversationID:
          record.chatLog.sessionType === 1
            ? 'si_' + record.chatLog.recvID + '_' + record.chatLog.sendID
            : 'sg_' + record.chatLog.recvID,
        userID: storage.get('userId'),
        seq: record.chatLog.seq
      })
      if (response || response.data) {
        const { errCode, errMsg } = response
        if (response?.errCode === 0) {
          message.success('消息撤回成功')
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }
  const showDrawer = () => {
    setOpen(true)
  }

  const onClose = () => {
    setOpen(false)
  }
  const cardDetails = (content: any) => {
    const { textElem, pictureElem, videoElem, createTime, senderNickname } = content || {}
    return (
      <div>
        <Flex justify="space-between">
          <div>{senderNickname}</div>
          <div>{dayjs(createTime).format('YYYY-MM-DD')}</div>
        </Flex>
        <Flex style={{ marginTop: 20 }}>{cardContentDetails(content)}</Flex>
        <Divider style={{ borderColor: '#7cb305' }}></Divider>
      </div>
    )
  }
  const cardContentDetails = (content: any) => {
    if (content.textElem) {
      return content.textElem.content
    } else if (content.pictureElem) {
      return <Image src={content?.pictureElem?.bigPicture?.url} height={200}></Image>
    } else if (content.videoElem) {
      return (
        <video
          src={content?.videoElem?.videoUrl}
          controls
          style={{ maxHeight: 500, maxWidth: 200 }}
        >
          {content?.videoElem.videoUrl}
        </video>
      )
    }
  }
  const cardContent = (content: {
    textElem: { content: any }
    pictureElem: any
    videoElem: any
  }) => {
    if (content.textElem) {
      return content.textElem.content
    } else if (content.pictureElem) {
      return '[图片]'
    } else if (content.videoElem) {
      return '[视频消息]'
    }
  }
  const card = (data: any) => {
    const { multiMessage } = data || {}

    return (
      <Card
        title={data?.title ?? ''}
        style={{ width: 300 }}
        onClick={() => {
          setCurrentMulInfo(data)
          showDrawer()
        }}
        hoverable
      >
        {multiMessage?.map((item: any, index: any) => {
          return (
            <p key={index}>
              {item.senderNickname}:{cardContent(item)}
            </p>
          )
        })}
      </Card>
    )
  }
  //   const [contentType, setContentType] = useState(101)
  return (
    <>
      <Spin spinning={loading} fullscreen size="large" />
      <ExcelTable
        actionRef={actionRef}
        form={{
          initialValues: {
            sendTime: dayjs()
          }
        }}
        requestFn={async params => {
          const {
            pageNum,
            pageSize,
            sendID = '',
            recvID = '',
            sendTime = dayjs().format('YYYY-MM-DD'),
            sessionType = null,
            contentType = null,
            ...newParams
          } = params // 处理所需参数名
          const data = await getUserMsg({
            ...newParams,
            pagination: { pageNumber: pageNum, showNumber: pageSize },
            sessionType: sessionType !== null ? parseInt(sessionType) : sessionType,
            contentType: contentType !== null ? parseInt(contentType) : contentType,
            recvID: recvID,
            sendID: sendID,
            sendTime: sendTime
          })
          return data
        }}
        rowSelection={false}
        toolBarRenderFn={() => []}
        columns={[
          /** search */
          {
            title: '消息类型',
            dataIndex: 'sessionType',
            hideInTable: true,
            valueType: 'select',
            valueEnum: {
              // null: '全部',
              1: '私聊',
              3: '群聊',
              4: '系统消息'
            }
          },
          {
            title: '会话类型',
            dataIndex: 'contentType',
            hideInTable: true,
            valueType: 'select',
            valueEnum: {
              null: '全部',
              101: '文本',
              102: '图片',
              104: '视频',
              105: '文件'
            }
          },
          {
            title: '发送时间',
            dataIndex: 'sendTime',
            valueType: 'date',
            hideInTable: true,
            fieldProps: {
              format: 'YYYY-MM-DD', // 日期格式
              picker: 'date' // 设置为日期选择器
            }
          },
          // {
          //   title: '操作内容',
          //   dataIndex: '',
          //   hideInTable: true
          // },
          /** table */
          {
            title: '序号',
            valueType: 'index',
            hideInSearch: true
          },
          {
            title: '内容',
            dataIndex: 'content',
            hideInSearch: true,
            // render: (_, record) => record.chatLog?.content || '暂无数据',
            render: (_, record) => {
              try {
                const contentType = record.chatLog?.contentType

                const parsedContent = JSON.parse(record.chatLog?.content)


                if (contentType === 104) {
                  return (
                    <video
                      src={parsedContent?.videoUrl}
                      controls
                      style={{ maxHeight: 100, maxWidth: 100 }}
                    >
                      {parsedContent.videoUrl}
                    </video>
                  )
                }
                if (contentType === 102) {
                  return <Image src={parsedContent?.bigPicture?.url} height={100}></Image>
                }

                if (contentType === 107) {
                  return card(parsedContent)
                }
                return parsedContent.content || '暂无数据'
              } catch (e) {
                return '暂无数据' // 如解析失败，返回默认值
              }
            },
            ellipsis: true, // 启用省略显示
            width: 400 // 最大宽度
          },
          {
            title: '消息类型',
            dataIndex: 'sessionType',
            hideInSearch: true,
            render: (_, record) => {
              const sessionType = record.chatLog?.sessionType
              if (sessionType === 1) {
                return '私聊'
              }
              if (sessionType === 3) {
                return '群聊'
              }
              // if (sessionType === 4) return '系统消息';
              return '暂无数据'
            }
          },
          {
            title: '发送者',
            dataIndex: 'senderNickname',
            hideInSearch: true,
            render: (_, record) => record.chatLog?.senderNickname || '暂无数据'
          },
          {
            title: '发送者ID',
            dataIndex: 'sendID',
            render: (_, record) => record.chatLog?.sendID || '暂无数据'
          },
          {
            title: '接收者',
            dataIndex: 'recvNickname',
            hideInSearch: true,
            render: (_, record) => {
              const sessionType = record.chatLog?.sessionType
              if (sessionType === 3) {
                return record.chatLog?.groupName || '暂无数据'
              }
              return record.chatLog?.recvNickname || '暂无数据'
            }
          },
          {
            title: '接收者ID',
            dataIndex: 'recvID',
            render: (_, record) => record.chatLog?.recvID || '暂无数据'
          },
          {
            title: '会话类型',
            dataIndex: 'contentType',
            hideInSearch: true,
            render: (_, record) => {
              const sessionType = record.chatLog?.contentType
              if (sessionType === 101) {
                return '文本'
              }
              if (sessionType === 102) {
                return '图片'
              }
              if (sessionType === 104) {
                return '视频'
              }
              if (sessionType === 105) {
                return '文件'
              }
              if (sessionType === 107) {
                return '转发消息'
              }
              return '暂无数据'
            }
          },
          {
            title: '发送时间',
            dataIndex: 'sendTime',
            hideInSearch: true,
            render: (_, record) =>
              record?.chatLog?.sendTime
                ? dayjs(Number(record?.chatLog?.sendTime)).format('YYYY-MM-DD HH:mm:ss')
                : '暂无数据'
          }
          // {
          //   title: '操作',
          //   key: 'option',
          //   valueType: 'option',
          //   render: (_, record) => [
          //     <a key="delete"
          //     style={{
          //         color: record.isRevoked ? '#ccc' : '#1890ff',
          //         pointerEvents: record.isRevoked ? 'none' : 'auto',
          //         cursor: record.isRevoked ? 'not-allowed' : 'pointer',
          //     }}
          //      onClick={() => {
          //         Modal.warning({
          //             title: '提示',
          //             content: '确定撤回该消息吗?',
          //             okText: '确定',
          //             okCancel: true,
          //             onOk() {
          //                 subRevoke(record)
          //             }
          //         })
          //     }}>{record.isRevoked?'消息已撤回':'撤回'}</a>
          //   ]
          // },
        ]}
      />
      <Drawer title={currentMulInfo.title} onClose={onClose} open={open}>
        {currentMulInfo?.multiMessage?.map((item: any, index: any) => {
          return <div key={index}>{cardDetails(item)}</div>
        })}
      </Drawer>
    </>
  )
}

export default UserMessage
